using System;
using System.Configuration;
using System.ServiceModel.Configuration;

namespace RockBus.ServiceModel.Diagnostics
{
    public class MessageLoggingBehaviorExtensionElement : BehaviorExtensionElement
    {
        private ConfigurationPropertyCollection _propertyCollection = null;

        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                if (this._propertyCollection == null)
                {
                    this._propertyCollection = new ConfigurationPropertyCollection();
                    this._propertyCollection.Add(new ConfigurationProperty("messageLoggingStages", typeof(string),
                        null, System.Configuration.ConfigurationPropertyOptions.IsRequired));
                    this._propertyCollection.Add(new ConfigurationProperty("maxBufferSize", typeof(int),
                        null, System.Configuration.ConfigurationPropertyOptions.None));
                }
                return this._propertyCollection;
            }
        }

        [ConfigurationProperty("messageLoggingStages", IsRequired = true)]
        public string MessageLoggingStages
        {
            get
            {
                return (string)base["messageLoggingStages"];
            }
            set
            {
                base["messageLoggingStages"] = value;
            }
        }

        [ConfigurationProperty("maxBufferSize", IsRequired = false)]
        public int? MaxBufferSize
        {
            get
            {
                if (!base.Properties.Contains("maxBufferSize"))
                {
                    return null;
                }
                return (int?)base["maxBufferSize"];
            }
            set
            {
                base["maxBufferSize"] = value;
            }
        }

        public override Type BehaviorType
        {
            get { return typeof(MessageLoggingBehavior); }
        }

        protected override object CreateBehavior()
        {
            string[] messageLoggingStagesStrings = this.MessageLoggingStages.Split(',');
            MessageLoggingStagesType messageLoggingStages = MessageLoggingStagesType.None;
            foreach (string messageLoggingStagesString in messageLoggingStagesStrings)
            {
                MessageLoggingStagesType mls = (MessageLoggingStagesType)Enum.Parse(typeof(MessageLoggingStagesType), messageLoggingStagesString, true);
                messageLoggingStages |= mls;
            }
            if (this.MaxBufferSize.HasValue)
            {
                return new MessageLoggingBehavior(messageLoggingStages, this.MaxBufferSize.Value);
            }

            return new MessageLoggingBehavior(messageLoggingStages);
        }
    }
}